package com.sw.bbs.board.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sw.bbs.board.service.MediaService;
import com.sw.bbs.common.util.ConstantQiniu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Desc: No Desc
 * @Author: wusonghe
 * @Date: 2019/4/1 17:17
 */
@Service
@Slf4j
public class MediaServiceImpl implements MediaService {

    @Autowired
    private ConstantQiniu constantQiniu;

    @Override
    public String upload(MultipartFile multipartFile) throws IOException {

        FileInputStream file = (FileInputStream) multipartFile.getInputStream();
        String key = multipartFile.getOriginalFilename();

        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        // 其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        // 生成上传凭证，然后准备上传
        try {
            Auth auth = Auth.create(constantQiniu.getAccessKey(), constantQiniu.getSecretKey());
            String upToken = auth.uploadToken(constantQiniu.getBucket());

            try {

                byte[] byt = new byte[file.available()];
                file.read(byt);
                Response response = uploadManager.put(byt, key, upToken);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                String returnPath = constantQiniu.getPath() + "/" + putRet.key;
                return returnPath;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
